/*  
 *  Nanjing JIYU Technology Co.,Ltd All rights reserved.
 *  Copyright (C) 2022 
 *  ==============================================================
 * 
 *  uart.c 
 *    系统用到的uart配置
 *
 *  --------------------------------------------------------------
 *  
 */

#include "uart.h"

#include "status.h"


/*--------------------------  UART3,用于和上位机通信  ----------------------------*/

/* 存储串口数据 */
volatile u8 uart3_rx_data = '0';

UART_HandleTypeDef uart3_handle;


void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
  //GPIO端口设置
  GPIO_InitTypeDef gpio_config;

  __HAL_RCC_GPIOB_CLK_ENABLE();      //使能GPIOB时钟
  __HAL_RCC_USART3_CLK_ENABLE();      //使能USART1时钟
  __HAL_RCC_AFIO_CLK_ENABLE();

  gpio_config.Pin = GPIO_PIN_10;      //PB10
  gpio_config.Mode = GPIO_MODE_AF_PP;    //复用推挽输出
  gpio_config.Pull = GPIO_PULLUP;      //上拉
  gpio_config.Speed = GPIO_SPEED_FREQ_HIGH;//高速
  HAL_GPIO_Init(GPIOB, &gpio_config);      //初始化PB

  gpio_config.Pin = GPIO_PIN_11;      //PB11
  gpio_config.Mode = GPIO_MODE_AF_INPUT;  //模式要设置为复用输入模式！
  HAL_GPIO_Init(GPIOB, &gpio_config);      //初始化PA10

  HAL_NVIC_EnableIRQ(USART3_IRQn);        //使能USART1中断通道
  HAL_NVIC_SetPriority(USART3_IRQn, 0, 0);      //抢占优先级3，子优先级3
}


void uart3_init(void)
{
  uart3_handle.Instance = USART3;
  uart3_handle.Init.BaudRate = 115200;
  uart3_handle.Init.WordLength = UART_WORDLENGTH_8B;
  uart3_handle.Init.StopBits = UART_STOPBITS_1;
  uart3_handle.Init.Parity = UART_PARITY_NONE;
  uart3_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  uart3_handle.Init.Mode = UART_MODE_TX_RX;

  HAL_UART_Init(&uart3_handle);

  /*使能串口接收断 */
  __HAL_UART_ENABLE_IT(&uart3_handle, UART_IT_RXNE);
}

/*--------------------------  UART3中断服务  ----------------------------*/

void USART3_IRQHandler(void)
{
  if (__HAL_UART_GET_FLAG(&uart3_handle, UART_FLAG_RXNE) != RESET)
  {
    uart3_rx_data = (uint16_t) READ_REG(uart3_handle.Instance->DR);

    status.new_msg++;
  }
}


/*--------------------------  UART3调试发送  ----------------------------*/
void uart3_send(uint8_t *str)
{
  unsigned int k = 0;
  do
  {
    HAL_UART_Transmit(&uart3_handle, (uint8_t * )(str + k), 1, 1000);
    k++;
  } while (*(str + k) != '\0');

}
/* 重定向 使用printf scanf调试 */
#pragma import(__use_no_semihosting)

struct __FILE
{
  int handle;
};

FILE __stdout;

void _sys_exit(int x)
{
  x = x;
}

int fputc(int ch, FILE *f)
{
  HAL_UART_Transmit(&uart3_handle, (uint8_t * ) & ch, 1, 1000);
  return (ch);
}

int fgetc(FILE *f)
{
  int ch;
  HAL_UART_Receive(&uart3_handle, (uint8_t * ) & ch, 1, 1000);
  return (ch);
}

